#include <func.h>

// 客户端
int main(void)
{
    int sock_fd = socket(AF_INET, SOCK_DGRAM, 0);
    if(sock_fd == -1)
        error(1, errno, "socket");

    int epoll_fd = epoll_create(1);
    if(epoll_fd == -1)
        error(1, errno, "epoll_create");

    // 在 epoll 对象监听集合中加入 socket ，监听读
    struct epoll_event event;
    event.events = EPOLLIN;
    event.data.fd = sock_fd;
    if(epoll_ctl(epoll_fd, EPOLL_CTL_ADD, sock_fd, &event) == -1)
        error(1, errno, "epoll_ctl");

    // 在 epoll 对象监听集合中加入 stdin ，监听读
    event.events = EPOLLIN;
    event.data.fd = STDIN_FILENO;
    if(epoll_ctl(epoll_fd, EPOLL_CTL_ADD, STDIN_FILENO, &event) == -1)
        error(1, errno, "epoll_ctl");

    struct sockaddr_in addr;
    addr.sin_family = AF_INET;
    addr.sin_port = htons(atoi("8080"));
    addr.sin_addr.s_addr = inet_addr("127.0.0.1");
    while(1)
    {
        struct epoll_event event[2];
        int count = epoll_wait(epoll_fd, event, 2, 1000);

        for(int i = 0; i < count; ++i)
        {
            int current_fd = event[i].data.fd;
            if(current_fd == STDIN_FILENO)
            {
                char buf[50] = {0};
                ssize_t ret = read(STDIN_FILENO, buf, 50);
                switch(ret)
                {
                case 0:
                    printf("111\n");
                    sendto(sock_fd, buf, 0, 0,(struct sockaddr*)&addr, sizeof(addr));
                    _exit(1);
                    break;
                default:
                    sendto(sock_fd, buf, ret, 0, (struct sockaddr*)&addr, sizeof(addr));
                }
            }

            if(current_fd == sock_fd)
            {
                char buf[50] = {0};
                ssize_t ret = recvfrom(sock_fd, buf, 50, 0, NULL, NULL);
                switch(ret)
                {
                case 0:
                    // 使用 udp 协议无法识别这个
                    fprintf(stderr, "对方已离线\n");
                    _exit(1);
                default:
                    printf("server: %s\n", buf);
                }
            }
        }
    }

    close(sock_fd);
    close(epoll_fd);
    return 0;
}

